/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    ScrollView,

} from 'react-native';

import NavBar from '../../components/NavBarView'
import State from '../../components/DemandStateView'
import {
    FormStatus,
    FormEvent,
    SubmitBtn,
    DefaultFieldType,
    DefaultField,
    DefaultInput,
    DefaultTextArea,
    DefaultLabel,
    DefaultUpload
} from '../../components/Form'
import AlertPopup from '../../components/AlertPopupModal'
import DemandService from '../../services/Demand'
import SystemService from '../../services/System'

let _self;

const validRule = {
    asset_type_id: {
        required: true
    },
    asset_type: {
        required: true
    },
    second_classify_id: {
        required: true
    },
    second_classify: {
        required: true
    },
    industry_name: {
        required: true
    },
    asset_name: {
        required: true
    },
    asset_subject: {
        required: true
    },
    capital_amount: {
        required: true,
        regExp: /^(\d|[1-9]\d+)(\.\d{1,4})?$/,
        errorMsg: '请输入最多4位小数的用款金额'
    },
    capital_term: {
        required: true,
        regExp: /\d/,
        errorMsg: '请输入1-999月的用款期限'
    },
    capital_interest_rate: {
        required: true,
        regExp: /^(\d|[1-9]\d+)(\.\d{1,2})?$/,
        errorMsg: '请输入最多2位小数且小于100%的期望利息'
    },
    repayment_source: {
        required: true
    },
    capital_purpose: {
        required: true
    },
    asset_describe: {
        required: true
    },
    require_file_id: {
        required: false
    }
};

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;
        this.state = {
            formStatus: FormStatus.EDIT,
            form: {
                asset_type_id: '',
                asset_type: '',
                second_classify_id: '',
                second_classify: '',
                industry_name: '',
                asset_name: '',
                asset_subject: '',
                capital_amount: '',
                capital_term: '',
                capital_interest_rate: '',
                repayment_source: '',
                capital_purpose: '',
                asset_describe: '',
                require_file_id: ''
            },
            selectedItem: {}, //已选类型item
            industry: [],
            loadingShow: true,
            authShow: false
        };
        const params = this.props.navigation.state.params;
        this.state.selectedItem = params.selectedItem;
        this.state.form.asset_type_id = params.selectedItem.id;
        this.state.form.asset_type = params.selectedItem.asset_type_name;
        //判断子类型存在且唯一时 选中唯一项
        if (params && params.selectedItem && params.selectedItem.children && params.selectedItem.children.length === 1) {
            this.state.form.second_classify_id = params.selectedItem.children[0].id;
            this.state.form.second_classify = params.selectedItem.children[0].asset_type_name;
        }
    }

    componentWillMount() {

    }

    componentDidMount() {
        this.load();
        this.auth();
    }

    async auth() {
        const {result, message, data} = await DemandService.check();
        if (result) {
            _self.setState({
                authShow: !data.allow_flag
            })
        } else {
            Toast.show(message);
        }
    }

    async load() {
        const {result, message, data} = await SystemService.getIndustry();
        if (result) {
            const industry = data.industry;
            _self.setState({industry})
        } else {
            Toast.show(message)
        }
    }

    selectIndustry() {
        FormEvent.picker({
            data: this.state.industry,
            title: '所属行业',
            handleConfirm(data) {
                _self.inputChange('industry_name', data.join('-'));
            }
        });
    }

    selectAssetType() {
        _self.props.navigation.navigate('AssetTypeList', {
            result({asset_type_id, asset_type, selectedItem}){
                if (asset_type_id !== _self.state.form.asset_type_id) {
                    let form = _self.state.form;
                    form.asset_type = asset_type;
                    form.asset_type_id = asset_type_id;
                    form.second_classify_id = '';
                    form.second_classify = '';
                    //判断子类型存在且唯一时 选中唯一项
                    if (selectedItem && selectedItem.children && selectedItem.children.length === 1) {
                        form.second_classify_id = selectedItem.children[0].id;
                        form.second_classify = selectedItem.children[0].asset_type_name;
                    }
                    _self.setState({form, selectedItem}, () => {
                        setTimeout(() => {
                            _self.setState({
                                formStatus: FormEvent.isCompleted(validRule, _self.state.form)
                            })
                        }, 200);
                    })
                }
            }
        })
    }

    selectSecondClassify() {
        _self.props.navigation.navigate('AssetTypeChildrenList', {
            list: this.state.selectedItem.children,
            selectedNames: this.state.form.second_classify,
            selectedIds: this.state.form.second_classify_id,
            result({second_classify_id, second_classify}){
                let form = _self.state.form;
                form.second_classify_id = second_classify_id;
                form.second_classify = second_classify;
                _self.setState({form}, () => {
                    setTimeout(() => {
                        _self.setState({
                            formStatus: FormEvent.isCompleted(validRule, _self.state.form)
                        })
                    }, 200);
                });
            }
        })
    }

    //input改变触发
    inputChange(key, value) {
        let form = _self.state.form;
        form[key] = value;
        _self.setState({form}, () => {
            setTimeout(() => {
                _self.setState({
                    formStatus: FormEvent.isCompleted(validRule, _self.state.form)
                })
            }, 200);
        });
    }

    async uploadFile(uri, loadingStart, loadingEnd) {
        let options = {
            params: {uri}
        };
        loadingStart();
        const {result, message, data} = await DemandService.upload(options);
        loadingEnd();
        if (result) {
            let form = _self.state.form;
            form.require_file_id = data && data.id ? data.id : '';
            _self.setState({form})
        } else {
            Toast.show(message);
        }
    }

    async submit() {
        const {result, message} = FormEvent.isValid(validRule, _self.state.form);
        if (result) {
            _self.setState({formStatus: FormStatus.SUBMITTING});
            const {result, message, data} = await DemandService.submit({params: _self.state.form});
            _self.setState({formStatus: FormStatus.READY});
            if (result) {
                Toast.show('发布成功');
                _self.props.navigation.navigate('DemandDetail', {
                    id: data.require_id,
                    type: 'add'
                })
            } else {
                Toast.show(message);
            }
        } else {
            Toast.show(message);
        }
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this} title="需求对接"/>
                <ScrollView style={styles.container}>
                    <State activeIndex={0} icons={[
                        require('../../sources/icon_demand_progress_1.png'),
                        require('../../sources/icon_demand_progress_2.png'),
                        require('../../sources/icon_demand_progress_3.png'),
                    ]}/>
                    <DefaultField text="资产类型">
                        <DefaultLabel
                            onPress={() => this.selectAssetType()}
                            rightIcon={require('../../sources/icon_global_go.png')}
                            inputValue={this.state.form.asset_type}
                            placeholder="请选择资产类型"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    {
                        this.state.form.asset_type === '其他' ?
                            <DefaultField text="二级分类">
                                <DefaultInput
                                    onChangeText={(text) => this.inputChange('second_classify', text)}
                                    maxLength={10}
                                    inputValue={this.state.form.second_classify}
                                    placeholder="请输入自定义资产类型"
                                    control={this.state.formStatus}/>
                            </DefaultField> :
                            <DefaultField text="二级分类">
                                <DefaultLabel
                                    onPress={() => this.selectSecondClassify()}
                                    rightIcon={require('../../sources/icon_global_go.png')}
                                    inputValue={this.state.form.second_classify}
                                    placeholder="请选择二级分类"
                                    control={this.state.formStatus}/>
                            </DefaultField>
                    }
                    <DefaultField text="所属行业">
                        <DefaultLabel
                            onPress={() => this.selectIndustry()}
                            rightIcon={require('../../sources/icon_global_go.png')}
                            inputValue={this.state.form.industry_name}
                            placeholder="请选择所属行业"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField text="项目名称">
                        <DefaultInput
                            onChangeText={(text) => this.inputChange('asset_name', text)}
                            maxLength={50}
                            inputValue={this.state.form.asset_name}
                            placeholder="请输入项目名称"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField text="项目主体">
                        <DefaultInput
                            onChangeText={(text) => this.inputChange('asset_subject', text)}
                            maxLength={50}
                            inputValue={this.state.form.asset_subject}
                            placeholder="请输入项目主体"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField text="用款金额">
                        <DefaultInput
                            keyboardType="numeric"
                            suffix="万元"
                            onChangeText={(text) => this.inputChange('capital_amount', text)}
                            maxLength={8}
                            inputValue={this.state.form.capital_amount}
                            placeholder="请输入用款金额"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField text="用款期限">
                        <DefaultInput
                            keyboardType="number-pad"
                            suffix="月"
                            onChangeText={(text) => this.inputChange('capital_term', text)}
                            maxLength={3}
                            inputValue={this.state.form.capital_term}
                            placeholder="请输入用款期限"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField text="期望成本">
                        <DefaultInput
                            keyboardType="numeric"
                            suffix="%"
                            onChangeText={(text) => this.inputChange('capital_interest_rate', text)}
                            maxLength={5}
                            inputValue={this.state.form.capital_interest_rate}
                            placeholder="请输入期望成本"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="资金用途">
                        <DefaultTextArea
                            onChangeText={(text) => this.inputChange('capital_purpose', text)}
                            maxLength={50}
                            inputValue={this.state.form.capital_purpose}
                            placeholder="请输入资金用途"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="还款来源">
                        <DefaultTextArea
                            onChangeText={(text) => this.inputChange('repayment_source', text)}
                            maxLength={50}
                            inputValue={this.state.form.repayment_source}
                            placeholder="请输入还款来源"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="资产描述">
                        <DefaultTextArea
                            onChangeText={(text) => this.inputChange('asset_describe', text)}
                            maxLength={1000}
                            inputValue={this.state.form.asset_describe}
                            placeholder="请输入资产描述"
                            control={this.state.formStatus}/>
                    </DefaultField>
                    <DefaultField type={DefaultFieldType.BLOCK} text="上传资产相关资料照片" subText="（非必填）">
                        <DefaultUpload
                            title="选择资产相关资料"
                            updateEvent={(uri, loadingStart, loadingEnd) => this.uploadFile(uri, loadingStart, loadingEnd)}
                            control={this.state.formStatus}/>
                    </DefaultField>
                </ScrollView>
                <View style={styles.btnBox}>
                    <SubmitBtn
                        style={styles.btn}
                        onPress={() => this.submit()}
                        control={this.state.formStatus}
                        text="发布需求"/>
                </View>
                <AlertPopup
                    text="请先认证"
                    cancelOnPress={() => {
                        this.setState({
                            authShow: false
                        });
                        this.props.navigation.goBack()
                    }}
                    visible={this.state.authShow}
                    btnOnPress={() => {
                        this.setState({
                            authShow: false
                        });
                        this.props.navigation.navigate('AuthList', {type: 'demand'})
                    }}/>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff'
    },
    btnBox: {
        paddingHorizontal: layout.GAP_HORIZONTAL_SMALL,
        paddingVertical: layout.GAP_VERTICAL_SMALL,
        backgroundColor: '#fff'
    },
    btn: {
        marginTop: 0,
        height: layout.height(90)
    }
})

//路由
const DemandForm = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'DemandForm',
    sign: true
};

export default DemandForm;